package com.tanhua.app.service;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.api.CommentApi;
import com.tanhua.api.UserInfoApi;
import com.tanhua.app.exception.BusinessException;
import com.tanhua.app.exception.ErrorResult;
import com.tanhua.app.interceptor.UserHolder;
import com.tanhua.commons.utils.Constants;
import com.tanhua.model.enums.CommentType;
import com.tanhua.model.mongo.Comment;
import com.tanhua.model.pojo.UserInfo;
import com.tanhua.model.vo.CommentVo;
import com.tanhua.model.vo.PageResult;
import org.apache.dubbo.config.annotation.DubboReference;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
public class CommentsService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @DubboReference
    private CommentApi commentApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    //发布评论
    public void saveComments(String movementId, String comment) {
        //1 封装评论对象
        Comment commentData = new Comment();
        commentData.setPublishId(new ObjectId(movementId));
        commentData.setCommentType(CommentType.COMMENT.getType());
        commentData.setContent(comment);
        commentData.setUserId(UserHolder.getUserId());
        commentData.setCreated(System.currentTimeMillis());

        //2 执行保存评论数据 通用的互动数据保存
        commentApi.save(commentData);
    }

    //分页查询评论列表
    public PageResult findComments(String movementId, Integer page, Integer pagesize) {
        //1 根据动态ID  调用Api  分页查询评论列表
        List<Comment> commentList = commentApi.findComments(movementId, CommentType.COMMENT, page, pagesize);

        //2 判断查询结果是否为空，为空直接返回
        if (CollUtil.isEmpty(commentList)) {
            return new PageResult(page, pagesize, 0, null);
        }

        //3 查询评论人的用户详情
        List<Long> ids = commentList.stream()
                .map(Comment::getUserId).collect(Collectors.toList());
        Map<Long, UserInfo> map = userInfoApi.findByIds(ids).stream()
                .collect(Collectors.toMap(UserInfo::getId, Function.identity()));

        //4 封装vos对象
        List<CommentVo> vos = new ArrayList<>();
        for (Comment comment : commentList) {
            UserInfo userInfo = map.get(comment.getUserId());
            if (userInfo != null) {
                CommentVo vo = CommentVo.init(userInfo, comment);
                vos.add(vo);
            }
        }

        //5 返回分页对象
        return new PageResult(page, pagesize, 0, vos);
    }

    //点赞
    public Integer likeComment(String movementId) {
        //1 查询点赞数据是否存在
        boolean hasLike = commentApi.hasLike(movementId, UserHolder.getUserId(), CommentType.LIKE);

        //2 判断并返回结果   不存在就可以点赞，可以往下走     存在就有问题，不能重复点赞
        if (hasLike) {
            throw new BusinessException(ErrorResult.likeError());
        }

        //3 封装点赞数据并保存
        Comment comment = new Comment();
        comment.setPublishId(new ObjectId(movementId));
        comment.setCommentType(CommentType.LIKE.getType());
        comment.setUserId(UserHolder.getUserId());
        comment.setCreated(System.currentTimeMillis());
        Integer count = commentApi.save(comment);

        //4 保存点赞数据到redis中  使用hash存储  大key就是动态的id    里面的小key是用户id
        String key = Constants.MOVEMENTS_INTERACT_KEY + movementId;
        String hashKey = Constants.MOVEMENT_LIKE_HASHKEY + UserHolder.getUserId();
        redisTemplate.opsForHash().put(key, hashKey, "1");

        //5 返回点赞后的总记录数
        return count;
    }

    //取消点赞
    public Integer dislikeComment(String movementId) {
        //1 查询点赞数据是否存在
        boolean hasLike = commentApi.hasLike(movementId, UserHolder.getUserId(), CommentType.LIKE);

        //2 判断点赞数据是否不存在，如果没有点赞数据，就不需要取消点赞
        if (!hasLike) {
            throw new BusinessException(ErrorResult.disLikeError());
        }

        //3 调用API执行删除点赞数据的操作    通用删除互动数据
        Integer count = commentApi.delete(movementId, UserHolder.getUserId(), CommentType.LIKE);

        //4 删除在redis缓存中的点赞数据
        String key = Constants.MOVEMENTS_INTERACT_KEY + movementId;
        String hashKey = Constants.MOVEMENT_LIKE_HASHKEY + UserHolder.getUserId();
        redisTemplate.opsForHash().delete(key, hashKey);

        //5 返回取消点赞后的总记录数
        return count;
    }

    //喜欢
    public Integer loveComment(String movementId) {
        //1 查询喜欢数据是否存在
        boolean hasLove = commentApi.hasLike(movementId, UserHolder.getUserId(), CommentType.LOVE);

        //2 判断并返回结果   不存在就可以喜欢，可以往下走     存在就有问题，不能重复喜欢
        if (hasLove) {
            throw new BusinessException(ErrorResult.loveError());
        }

        //3 封装喜欢数据并保存
        Comment comment = new Comment();
        comment.setPublishId(new ObjectId(movementId));
        comment.setCommentType(CommentType.LOVE.getType());
        comment.setUserId(UserHolder.getUserId());
        comment.setCreated(System.currentTimeMillis());
        Integer count = commentApi.save(comment);

        //4 保存喜欢数据到redis中  使用hash存储  大key就是动态的id    里面的小key是用户id
        String key = Constants.MOVEMENTS_INTERACT_KEY + movementId;
        String hashKey = Constants.MOVEMENT_LOVE_HASHKEY + UserHolder.getUserId();
        redisTemplate.opsForHash().put(key, hashKey, "1");

        //5 返回喜欢后的总记录数
        return count;
    }

    //取消喜欢
    public Integer unlove(String movementId) {
        //1 查询喜欢数据是否存在
        boolean hasLove = commentApi.hasLike(movementId, UserHolder.getUserId(), CommentType.LOVE);

        //2 判断喜欢数据是否不存在，如果没有喜欢数据，就不需要取消喜欢
        if (!hasLove) {
            throw new BusinessException(ErrorResult.disloveError());
        }

        //3 调用API执行删除喜欢数据的操作    通用删除互动数据
        Integer count = commentApi.delete(movementId, UserHolder.getUserId(), CommentType.LOVE);

        //4 删除在redis缓存中的喜欢数据
        String key = Constants.MOVEMENTS_INTERACT_KEY + movementId;
        String hashKey = Constants.MOVEMENT_LOVE_HASHKEY + UserHolder.getUserId();
        redisTemplate.opsForHash().delete(key, hashKey);

        //5 返回取消喜欢后的总记录数
        return count;
    }
}
